package chapter12_并发程序的测试.正确性测试;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class BoundedBufferTest {

    @Test
    public void testIsEmptyWhenConstructed() {
        BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);
        assertTrue(bb.isEmpty());
        assertFalse(bb.isFull());
    }

    @Test
    public void testIsFullAfterPuts() throws InterruptedException {
        BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);
        for (int i = 0; i < 10; i++) {
            bb.put(i);
        }
        assertTrue(bb.isFull());
        assertFalse(bb.isEmpty());
    }

    @Test
    public void testTakeBlocksWhenEmpty() {
        final BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);
        Thread take = new Thread() {
            @Override
            public void run() {
                try {
                    int unused = bb.take();
                    fail();
                } catch (InterruptedException success) {
                }
            }
        };
        try {
            take.start();
            Thread.sleep(3 * 1000);
            take.interrupt();
            take.join(3 * 1000);
            assertFalse(take.isAlive());
        } catch (Exception unexpected) {
            fail();
        }
    }

    private void fail() {
        System.out.println("测试失败");
        throw new IllegalStateException("test fail.");
    }
}
